package com.lv.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.tea.TeaException;
import com.lv.data.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("mq")
public class MessageController {

    @Autowired
    private Client client;

    @Value("${dysms.signName}")
    private String signName;

    @Value("${dysms.templateCode}")
    private String templateCode;

    @Autowired
    private StringRedisTemplate redis;

    //发送短信
    @PostMapping("sendMessage")
    public Result sendMessage(@RequestParam String phoneNum){
        String s = RandomStringUtils.randomNumeric(4);
        JSONObject json = new JSONObject();
        json.put("sms_code",s);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(phoneNum)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(json.toJSONString());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        redis.opsForValue().set(phoneNum,s,5, TimeUnit.MINUTES);
        return Result.OK();
    }
}
